//------------------------------------------------------------------------------
//  <copyright file="Microsoft.Robotics.Manipulation.KukaPipelineAPI.cpp" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------
#include "stdafx.h"
#include "Microsoft.Robotics.Hardware.KukaPipelineAPI.h"
#include <FriServer.h>
#include <Windows.h>

using namespace Microsoft::Robotics::Hardware::KukaLBR;

/// <summary> Creates a PipeLineApi class with callbacks to a managed FRI. </summary>
/// <param name="managedFRIConnection"> Managed FRI handler </param>
/// Object Creation
KukaPipelineAPI^ KukaPipelineAPI::Create(IManagedFRI^ managedApi)
{
    pin_ptr<volatile long> pCount = &KukaPipelineAPI::creationCount;
    if (InterlockedIncrement(pCount) == 1)
    {
        KukaPipelineAPI::singleton = gcnew KukaPipelineAPI(managedApi);
    }

    while (nullptr == KukaPipelineAPI::singleton)
    {
        Sleep(10);
    }

    return KukaPipelineAPI::singleton;
}


/// <summary> Initializes a new instance of the <c>KukaPipelineAPI</c> class with callbacks to a managed FRI. </summary>
/// <param name="managedFRIConnection"> Managed FRI handler </param>
KukaPipelineAPI::KukaPipelineAPI(IManagedFRI^ managedFRIConnection)
{
    this->Initialize(managedFRIConnection);
}

/// <summary> class destructor - On final destruction release unmanged resources. </summary>
KukaPipelineAPI::~KukaPipelineAPI()
{
	GC::SuppressFinalize(this);

    pin_ptr<volatile long> pCount = &KukaPipelineAPI::creationCount;
    if (0 == InterlockedDecrement(pCount) )
    {
		this->CleanUpUnmanagedResources();

		// clean up managed resources in dtor
        if (nullptr != this->kukaThunkFri)
        {
            delete this->kukaThunkFri;
        }
    }
}

// <summary> class finalizer - release unmanaged resources </summary>
KukaPipelineAPI::!KukaPipelineAPI()
{
    pin_ptr<volatile long> pCount = &KukaPipelineAPI::creationCount;
    if (0 == InterlockedDecrement(pCount) )
    {
		// only cleanup unmanaged resources in finalizer
		this->CleanUpUnmanagedResources();
    }
}

/// <summary> clean up unmanaged resources
void KukaPipelineAPI::CleanUpUnmanagedResources()
{
	delete this->pController;
}

/// <summary> Initialize the API </summary>
/// <param name="managedApi">Optional managed FRI server. If null uses the default unmanaged FRIserver </param>
void KukaPipelineAPI::Initialize(IManagedFRI^ managedFRIConnection)
{
    this->kukaThunkFri = nullptr;
    
    // Regardless of how it is created pCurrentFri is the one that will be used
    // Normally it is owned by this class. But if a thunk layer is used then the FRI is owned by
    // the thunklayer obejct
    IFRIConnection *pCurrentFri;
    if (nullptr != managedFRIConnection)
    {
        this->kukaThunkFri = gcnew ManagedKukaFriThunk(managedFRIConnection);
        pCurrentFri = dynamic_cast<ManagedKukaFriThunk ^>(this->kukaThunkFri)->GetFriConnection();
    }
    else
    {
        pCurrentFri = new FRIServer();
        if (NULL == pCurrentFri)
        {
            throw gcnew Exception("Failed to create an unmanaged Kuka FRI server - unable to initialize up pipeline API");
        }
    }

    this->pController = new KukaLBR4PlusController();
    this->pClientMessageHandler = this->pController->StartKukaLBR4PlusController(pCurrentFri);
}


/// <summary> Wrapper to set the controller state machine</summary>
/// <param name="pStateMachine">Pointer to state machine </param>
bool KukaPipelineAPI::SetStateMachineMessage(void *pvStateMachine)
{
    ControllerStateMachineDescription *pStateMachine = (ControllerStateMachineDescription *)pvStateMachine;
    return SetStateMachineMessage(pStateMachine);
}

/// <summary> Set the controller state machine</summary>
/// <param name="pStateMachine">Pointer to state machine </param>
bool KukaPipelineAPI::SetStateMachineMessage(ControllerStateMachineDescription *pStateMachine)
{
    MessageDescription *pMessage = new MessageDescription(sizeof(*pStateMachine));
    pMessage->MessageType = MessageTypes::SetCsmdMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = sizeof(*pStateMachine);
    memcpy_s(
			pMessage->pParameters,
			pMessage->ParameterBufferLength,
			pStateMachine,
			sizeof(*pStateMachine));

    MessageDescription *pResponse = new MessageDescription(sizeof(KukaFeedbackMessage));
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);

    bool status = (pResponse->pParameters[0] == 1);
    delete pMessage;
    delete pResponse;
    return status;
}

/// <summary>Query for controller feedback registers</summary>
/// <returns>Managed version of feedback registers or null if cannot get feedback registers <returns>
FeedbackMessageManaged^ KukaPipelineAPI::GetFeedbackMessage()
{
    MessageDescription *pMessage = new MessageDescription(0);
    pMessage->MessageType = MessageTypes::GetFeedbackMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = 0;

    MessageDescription *pResponse = new MessageDescription(sizeof(KukaFeedbackMessage));
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);
	FeedbackMessageManaged ^ feedbackMessageManaged = nullptr;

	if (pResponse->ParameterLength == sizeof(KukaFeedbackMessage))
	{
		KukaFeedbackMessage feedbackMessage;
		memcpy_s(
			&feedbackMessage,
			sizeof(KukaFeedbackMessage),
			pResponse->pParameters,
			pResponse->ParameterLength);

		feedbackMessageManaged = gcnew FeedbackMessageManaged(&feedbackMessage);
	}

    delete pMessage;
    delete pResponse;

    return feedbackMessageManaged;
}

/// <summary> Set the controller working registers</summary>
/// <param name="pStateMachine">Register values </param>
/// <returns> Return code  true for no error </returns>
bool KukaPipelineAPI::SetWorkingRegisters(WorkingRegisterMessageManaged ^workingRegisters)
{
    int messageLength = sizeof(KukaWorkingRegisterMessage);
    MessageDescription *pMessage = new MessageDescription(messageLength);
    pMessage->MessageType = MessageTypes::SetWorkingRegistersMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = messageLength;

    KukaWorkingRegisterMessage registerMessage;
    workingRegisters->CopyToUnmanaged(&registerMessage);
    memcpy_s(
        pMessage->pParameters,
        pMessage->ParameterBufferLength,
        &registerMessage,
        sizeof(registerMessage));

    MessageDescription *pResponse = new MessageDescription(1);
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);

    bool status = (pResponse->pParameters[0] == 1);
    delete pMessage;
    delete pResponse;
    return status;
}

/// <summary>Start the controller state machine</summary>
/// <returns> Return code  true for no error </returns>
bool KukaPipelineAPI::StartStateMachine()
{
    MessageDescription *pMessage = new MessageDescription(0);
    pMessage->MessageType = MessageTypes::StartCsmdMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = 0;
    pMessage->pParameters = NULL;
    MessageDescription *pResponse = new MessageDescription(1);
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);

    bool status = (pResponse->pParameters[0] == 1);
    delete pMessage;
    delete pResponse;
    return status;
}

/// <summary>Stop the controller state machine</summary>
/// <returns> Return code  true for no error </returns>
bool KukaPipelineAPI::StopStateMachine()
{
    MessageDescription *pMessage = new MessageDescription(0);
    pMessage->MessageType = MessageTypes::StopCsmdMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = 0;
    pMessage->pParameters = NULL;
    MessageDescription *pResponse = new MessageDescription(1);
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);

    bool status = (pResponse->pParameters[0] == 1);
    delete pMessage;
    delete pResponse;
    return status;
}

/// <summary>Clode the underlying FRI connection</summary>
/// <returns> Return code  true for no error </returns>
bool KukaPipelineAPI::CloseConnection()
{
    MessageDescription *pMessage = new MessageDescription(0);

    pMessage->MessageType = MessageTypes::ConnectionClosedMessageType;
    pMessage->IsResponse = 0;
    pMessage->ParameterLength = 0;
    pMessage->pParameters = NULL;
    MessageDescription *pResponse = new MessageDescription(1);
    this->pClientMessageHandler->ProcessMessage(pMessage, pResponse);

    delete pMessage;
    delete pResponse;

	// no status is given by ProcessMessage in response to close messages
	// so just return true;
    return true;
}
